import { useEffect } from "react"
import { useReducer } from "react"

// 1.创建初始化数据
const initalState = {
  count: 10,
  proList: []
}
// 2.设置reducer ----  唯一改变数据方式就是通过reducer实现
const reducer = (state, action) => {// action { type, payload }
  switch (action.type) {
    case 'ADD':
      return Object.assign({}, state, { count: state.count + action.payload })
    case 'CHANGE_PRO_LIST':
      return Object.assign({}, state, { proList: action.payload })
    default:
      return state
  }
}

// 有了useReducer，不需要useState, 但是企业项目一般不去这么使用
const App = () => {
  const [state, dispatch] = useReducer(reducer, initalState)

  useEffect(() => {
    fetch('http://121.89.205.189:3001/api/pro/list').then(res => res.json()).then(res => {
      dispatch({
        type: 'CHANGE_PRO_LIST',
        payload: res.data
      })
    })
  }, [])

  return (
    <div>
      { state.count } <button onClick={ () => {
        dispatch({
          type: 'ADD',
          payload: 5
        })
      }}>加5</button>
      <ul>
        {
          state.proList && state.proList.map(item => (
            <li key = { item.proid }>{ item.proname }</li>
          ))
        }
      </ul>
    </div>
  );
};

export default App;